<script lang="ts" setup>
import { Card, message } from 'ant-design-vue';
import { ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { useVbenForm } from '#/adapter/form';
import { getSampleDataApi, updateSampleDataApi } from '#/api';
import { confirmModal } from '#/components';
import dayjs, { Dayjs } from 'dayjs';
import 'dayjs/locale/zh-cn';
import { sampleFormSchemas, commonFormConfig } from './schemas';

const record = ref(); // 记录调用modal时传递过来的数据
const action = ref(); // 记录当前操作类型
const gridApi = ref(); // 记录调用时传递过来表格实例
const isCancel = ref(false); // 是否取消操作

// 默认值
const originalData = {
  sampleNo: 'WOSHIJIADE',
  orderNo: '/',
  clientName: '四川润泰特种气体有限公司',
  quantity: '1瓶',
  sampleStatus: '钢瓶，密封完好',
  currentProgress: '样品测试',
  receiver: '王孝利',
  sampleHandling: true,
};

const [BaseForm, BaseFormApi] = useVbenForm({
  ...commonFormConfig,
  ...sampleFormSchemas,
  showDefaultActions: false, // 不显示默认按钮
  wrapperClass: 'grid-cols-12',
});

/* 通过弹窗方式加载当前内容 */
const [VbenModal, modalApi] = useVbenModal({
  // fullscreen: true,  // 默认全屏
  confirmText: '提交',
  draggable: true,
  closeOnPressEscape: false,
  closeOnClickModal: false,

  onOpenChange(isOpen) {
    // 判断是打开还是关闭
    if (!isOpen) {
      if (!isCancel.value) gridApi.value?.query(); // 正常关闭就重新查询表格数据
      return;
    }
    record.value = modalApi.getData()?.record || {};
    action.value = modalApi.getData()?.whichAction || '';
    gridApi.value = modalApi.getData()?.gridApi || null;
    modalApi.setState({ title: action === 'new' ? '新增样品' : '编辑样品' });

    // 填充表单数据
    const whichData = action.value === 'new' ? originalData.sampleNo : record.value?.sampleNo;
    processData(whichData).catch((error) => {
      message.error('处理数据时出错：' + error.message || '未知错误');
      return;
    });
  },
  onConfirm() {
    return onSubmit();
  },
  onClosed() {
    // 关闭时重置表单
    BaseFormApi.resetForm();
  },
  onCancel() {
    isCancel.value = true;
    modalApi.close();
  },
});

/*==============================函数过程===============================*/
// 数据处理函数
let currentCreatedate: Dayjs;
async function processData(sampleNo: any) {
  try {
    if (!sampleNo) return new Error('未传递委托单号！');

    let data;
    if (sampleNo === 'WOSHIJIADE') {
      data = originalData;
      data.createTime = dayjs();
    } else {
      const res = await getSampleDataApi(sampleNo);
      data = res[0];
      data.sampleName = JSON.parse(data.sampleName);
      data.receiveDate = data.receiveDate ? <Dayjs>dayjs(data.receiveDate) : null;
      data.processDate = data.processDate ? <Dayjs>dayjs(data.processDate) : null;
      data.analysisDate = data.analysisDate ? <Dayjs>dayjs(data.analysisDate) : null;
      currentCreatedate = dayjs(data.fillDate);

      // 1转为true，0转为false
      data.sampleHandling = data.sampleHandling ? true : false;
    }

    // 表单赋值
    try {
      await BaseFormApi.setValues(data);
      return 'ok';
    } catch (error) {
      throw new Error('表单赋值时出错(' + error.message || '未知错误2' + ')');
    }
  } catch (error) {
    modalApi.close();
    throw new Error(error.message || '未知错误3');
  }
}

/*==============================表单事件===============================*/
async function onSubmit() {
  // 验证表单
  const isValid = await BaseFormApi.validate();
  if (!isValid.valid) {
    message.error({ content: '数据填写不完整，请检查！', key: 'beforeSubmit' });
    return;
  }
  // 二次确认
  const confirmRes = await confirmModal('提交确认', '即将提交数据，是否继续？');
  if (!confirmRes) return;

  try {
    // 锁定modal
    modalApi.lock();
    message.loading({
      content: '数据验证处理中，请稍后...',
      duration: 0,
      key: 'beforeSubmit',
    });

    const values = await BaseFormApi.getValues();
    // 格式化时间，避免时间格式不一致导致的问题
    values.receiveDate = dayjs(values.receiveDate).format('YYYY-MM-DD');
    values.processDate = dayjs(values.processDate).format('YYYY-MM-DD');
    values.analysisDate = dayjs(values.analysisDate).format('YYYY-MM-DD');
    if (action.value === 'new' || action.value === 'saveAs') {
      values.createTime = dayjs().format('YYYY-MM-DD HH:mm:ss'); // 登记时间
    } else {
      values.createTime = currentCreatedate.format('YYYY-MM-DD HH:mm:ss');
    }
    values.updateTime = dayjs().format('YYYY-MM-DD HH:mm:ss'); // 更新时间

    // 提交数据
    await updateSampleDataApi({
      action: action.value === 'edit' ? 'update' : 'insert',
      data: JSON.stringify(values),
    }).then(() => {
      message.success({ content: '提交成功', key: 'beforeSubmit', duration: 2 });
      modalApi.unlock();
      if (action.value === 'new' || action.value === 'saveas') {
        // 新增、另存为: 是否继续增加样品
        confirmModal('提交成功', '是否继续增加样品？').then((res) => {
          if (res) {
            modalApi.setState({ title: '新增样品' });
            BaseFormApi.resetForm();
            processData('WOSHIJIADE');
          } else {
            isCancel.value = false;
            modalApi.close();
          }
        });
      } else {
        isCancel.value = false;
        modalApi.close();
      }
    });
  } catch (error) {
    message.error({
      content: `提交失败：${error.message}`,
      key: 'beforeSubmit',
    });
  } finally {
    modalApi.unlock();
  }
}

/*==============================其他事件===============================*/

defineExpose(modalApi);
</script>

<template>
  <VbenModal class="w-[90%] h-auto">
    <Card>
      <BaseForm />
    </Card>
  </VbenModal>
</template>
